#include "command.h"

#include <stdlib.h>
#include <string.h>

static int cmd_set_pixel(Image* img, Command* cmd)
{
	CmdSetPixel* sp = &cmd->sp;

	if(sp->x > img->w-1 || sp->y > img->h-1)
		return 0;

	sp->_old_color = img->data[sp->x + (sp->y * img->w)];
	img->data[sp->x + (sp->y * img->w)] = sp->color;

	return -1;
}


static int cmd_set_pixel_undo(Image* img, Command* cmd)
{
	CmdSetPixel* sp = &cmd->sp;
	img->data[sp->x + (sp->y * img->w)] = sp->_old_color;
	return -1;
}


static int cmd_resize(Image* img, Command* cmd)
{
	cmd->rs._old_w = img->w;
	cmd->rs._old_h = img->h;
	printf("%d %d\n", cmd->rs.r.w, cmd->rs.r.h);
	cmd->rs._old_data = calloc(img->h * img->w, 1);
	memcpy(cmd->rs._old_data, img->data, (img->h * img->w));
	image_resize(img, cmd->rs.r);
	return -1;
}


static int cmd_resize_undo(Image* img, Command* cmd)
{
	img->w = cmd->rs._old_w;
	img->h = cmd->rs._old_h;
	free(img->data);
	img->data = calloc(img->h * img->w, 1);
	memcpy(img->data, cmd->rs._old_data, (img->h * img->w));
	return -1;
}


static int cmd_mirror(Image* img, Command* cmd)
{
	image_mirror(img, cmd->mr.inv);
	return -1;
}


static int cmd_rotate(Image* img, Command* cmd)
{
	image_rotate(img, cmd->ro.rot);
	return -1;
}


static int cmd_rotate_undo(Image* img, Command* cmd)
{
	image_rotate(img, cmd->ro.rot == CLOCKWISE ? ANTICLOCKWISE : CLOCKWISE);
	return -1;
}


void command_free(Command* cmd)
{
	switch(cmd->command)
	{
		case CMD_RESIZE:
			free(cmd->rs._old_data);
			break;
		default:
			break;
	}
	free(cmd);
}


CommandFunction command_functions[] = {
	{ cmd_set_pixel, cmd_set_pixel_undo },
	{ cmd_resize, cmd_resize_undo },
	{ cmd_mirror, cmd_mirror },
	{ cmd_rotate, cmd_rotate_undo },
};
